package com.xu.ai.mcp.asyncclient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * 响应式mcp客户端启动类
 *
 * @author xuguan
 * @since 2025/11/3
 */
@SpringBootApplication
public class AsyncMcpClientApplication {

	private static final Logger log = LoggerFactory.getLogger(AsyncMcpClientApplication.class);

	public static void main(String[] args) {
		SpringApplication.run(AsyncMcpClientApplication.class, args);
	}

	@Bean
	public CommandLineRunner toolCallback(ToolCallbackProvider toolCallbackProvider, ChatClient.Builder chatClientBuilder) {
		return new CommandLineRunner() {
			@Override
			public void run(String... args) throws Exception {
				final ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();
				StringBuilder sb = new StringBuilder();
				for (ToolCallback toolCallback : toolCallbacks) {
					final ToolDefinition td = toolCallback.getToolDefinition();
					sb.append(td.name()).append(": ").append(td.description())
							.append("\n");
				}

				var chatClient = chatClientBuilder
						.defaultToolCallbacks(toolCallbackProvider)
						.build();

				final String content = chatClient.prompt("calculate the result of add 2 and 3").call().content();
				System.out.println(content);
				log.info("Available tools: {}", sb.toString());
			}

		};
	}
}
